﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using JobDescOnline.Presentation.Models;
using eq.CoreBase.View;
using eq.CoreBase.Control;

namespace JobDescOnline.Presentation.Controllers
{
    public class CompetencyController : Controller
    {
        //
        // GET: /Competency/
        public JobDescDBEntities1 db = new JobDescDBEntities1();

        public ActionResult Index()
        {
            int pagesize = 10;
            int page = Request.QueryString["page"] != null ? Convert.ToInt16(Request.QueryString["page"]) : 1;
            string sort = Request.QueryString["sort"] != null ? Request.QueryString["sort"] : "ID";
            string direction = Request.QueryString["direction"] != null ? Request.QueryString["direction"] : "ASC";
            int total = 0;

            var model = Competencies.RetrieveByFilterAndPage(page, pagesize, sort, direction);
            total = Competencies.RetrieveByFilter();

            ViewData["Dir"] = direction.ToLower() == "asc" ? "desc" : "asc";

            PagingGenerated pager = new PagingGenerated(page, pagesize, total, "/Competency/AjaxTable", true, ">> next", true, "<< previous");
            ViewData["Pagination"] = pager.PaginationLink();
            return View(model);
        }

        public ActionResult AjaxTable()
        {
            int pagesize = 10;
            int page = Request.QueryString["page"] != null ? Convert.ToInt16(Request.QueryString["page"]) : 1;
            List<FilterData> filters = Request.Form["filter"] != null ? new JavaScriptSerializer().Deserialize<List<FilterData>>(Request.Form["filter"]) : new List<FilterData>();
            string sort = !string.IsNullOrEmpty(Request.QueryString["sort"]) ? Request.QueryString["sort"] : "ID";
            string direction = !string.IsNullOrEmpty(Request.QueryString["direction"]) ? Request.QueryString["direction"] : "ASC";

            dynamic model = null;
            int total = 0;

            if (filters.Count > 0)
            {
                model = Competencies.RetrieveByFilterAndPage(filters, page, pagesize, sort, direction);
                total = Competencies.RetrieveByFilter(filters);
            }
            else
            {
                model = Competencies.RetrieveByFilterAndPage(page, pagesize, sort, direction);
                total = Competencies.RetrieveByFilter();
            }

            if (total > 0) return View(model);
            else return View("Empty");
        }

        public ActionResult AjaxPaging()
        {
            int pagesize = 10;
            int page = Request.QueryString["page"] != null ? Convert.ToInt16(Request.QueryString["page"]) : 1;
            string sort = Request.QueryString["sort"] != null ? Request.QueryString["sort"] : "ID";
            string direction = Request.QueryString["direction"] != null ? Request.QueryString["direction"] : "ASC";
            List<FilterData> filters = Request.Form["filter"] != null ? new JavaScriptSerializer().Deserialize<List<FilterData>>(Request.Form["filter"]) : new List<FilterData>();
            int total = 0;

            if (filters.Count > 0)
            {
                total = Competencies.RetrieveByFilter(filters);
            }
            else
            {
                total = Competencies.RetrieveByFilter();
            }

            PagingGenerated pager = new PagingGenerated(page, pagesize, total, "/Competency/AjaxTable", true, ">> next", true, "<< previous");
            ViewData["Pagination"] = pager.PaginationLink();

            return View();
        }

        //
        // GET: /Competency/Create

        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /Competency/Create

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here
                Competency competency = db.Competencies.CreateObject();
                if (ModelState.IsValid)
                {
                    competency.Rowstatus = Convert.ToBoolean(collection["Rowstatus"]);
                    competency.Description = collection["Description"];
                    competency.Definition = collection["Definition"];
                    competency.CreatedBy = UserAuthenticated.isAuthenticated ? UserAuthenticated.authUser.FirstName : "DEFAULT";
                    competency.CreatedOn = DateTime.Now;

                    db.Competencies.AddObject(competency);
                    db.SaveChanges();
                }

                return RedirectToAction("Edit/" + competency.ID.ToString());
            }
            catch
            {
                return View();
            }
        }
        
        //
        // GET: /Competency/Edit/5
 
        public ActionResult Edit(int id)
        {
            CompetencyModel competencymodel = new CompetencyModel
            {
                Competency = db.Competencies.First(c => c.ID == id),
                LevelCompetencies = db.LevelCompetencies.Where(l => l.CompetencyID == id)
            };

            return View("Edit", competencymodel);
        }

        //
        // POST: /Competency/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here
                if (ModelState.IsValid)
                {
                    Competency competency = db.Competencies.First(d => d.ID == id);
                    competency.Rowstatus = Convert.ToBoolean(collection["Competency.Rowstatus"]);
                    competency.Description = collection["Competency.Description"];
                    competency.Definition = collection["Competency.Definition"];
                    competency.LastModifiedBy = UserAuthenticated.isAuthenticated ? UserAuthenticated.authUser.FirstName : "DEFAULT";
                    competency.LastModifiedOn = DateTime.Now;

                    db.Competencies.ApplyCurrentValues(competency);
                    db.SaveChanges();
                }

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Competency/Delete/5
 
        public ActionResult Delete(int id)
        {
            IEnumerable<LevelCompetency> levelcompetency = db.LevelCompetencies.Where(l => l.CompetencyID == id);
            foreach (LevelCompetency level in levelcompetency)
            {
                db.LevelCompetencies.DeleteObject(level);
            }
            Competency competency = db.Competencies.Single(d => d.ID == id);
            db.Competencies.DeleteObject(competency);
            db.SaveChanges();

            return RedirectToAction("Index");
        }
    }
}
